import { defineConfig, presetUno, presetAttributify, presetIcons } from "unocss"

const _width = 1920
const _height = 1080

const pxToViewportUnit = (px, designSize, viewportUnit) => {
  return `${(parseInt(px) / designSize) * 100}${viewportUnit}`
}

const createRule = (property, designSize, viewportUnit) => {
  return ([, size]) => ({
    [property]: pxToViewportUnit(size, designSize, viewportUnit)
  })
}
const createDirectionalRule = (prefix, property, designSize, viewportUnit) => {
  return ([, direction, size]) => {
    // 检查 size 是否为 undefined
    if (!size) {
      return {}
    }
    const sizeValue = size.replace(/px$/, "")
    const numericValue = parseFloat(sizeValue)
    if (isNaN(numericValue)) {
      return {}
    }
    let props = {}
    const directions = {
      x: ["left", "right"],
      y: ["top", "bottom"],
      l: ["left"],
      r: ["right"],
      t: ["top"],
      b: ["bottom"]
    }
    if (direction in directions) {
      directions[direction].forEach((dir) => {
        props[`${property}-${dir}`] = pxToViewportUnit(numericValue, designSize, viewportUnit)
      })
    } else {
      props[property] = pxToViewportUnit(numericValue, designSize, viewportUnit)
    }
    return props
  }
}

export default defineConfig({
  // ...UnoCSS options
  presets: [presetUno(), presetAttributify(), presetIcons()],
  rules: [
    [/^w-(\d+px)$/, createRule("width", _width, "vw")],
    [/^h-(\d+px)$/, createRule("height", _height, "vh")],
    [/^text-(\d+px)$/, createRule("font-size", _width, "vw")],
    [/^leading-(\d+px)$/, createRule("line-height", _height, "vh")],
    [/^border-(\d+px)$/, createRule("border-width", _width, "vw")],
    [/^rounded-(\d+px)$/, createRule("border-radius", _width, "vw")],

    [/^m(y|t|b)-(\d+px)$/, createDirectionalRule("m", "margin", _height, "vh")], // 上下边距基于高度
    [/^m(x|l|r)-(\d+px)$/, createDirectionalRule("m", "margin", _width, "vw")], // 左右边距基于宽度
    [
      /^m-(\d+px)$/,
      ([, size]) => createDirectionalRule("m", "margin", _width, "vw")(["", "", size])
    ],

    // Padding rules
    [/^p(y|t|b)-(\d+px)$/, createDirectionalRule("p", "padding", _height, "vh")], // 上下内边距基于高度
    [/^p(x|l|r)-(\d+px)$/, createDirectionalRule("p", "padding", _width, "vw")], // 左右内边距基于宽度
    [
      /^p-(\d+px)$/,
      ([, size]) => createDirectionalRule("p", "padding", _width, "vw")(["", "", size])
    ]
  ]
})
